'use strict'

const Titbit = require('titbit')
//require的返回值是一个object，属性有pqdb
const db = require('./lib/initdb').pqdb
//导入ORM和数据库配置
const psqlorm = require('psqlorm')
const database = require('./config/database.js')

//初始化ORM
let orm = psqlorm(db)
//设置默认的schema
orm.setSchema(database.schema)

const app = new Titbit({
  debug: true
})

app.get('/data', async ctx => {
  //select * from content order by create_time desc
  let datalist = await orm.model().table('content')
                          .order('create_time', 'desc')
                          .select()
  
  ctx.send({
    total: await orm.model().table('content').count(),
    list: datalist
  })
})

//写入一条数据到数据库
app.post('/data', async ctx => {
  //要求ctx.body携带和content表对应的属性
  /* let sql = `insert into content `
        + ` (id, title, detail, create_time)`
        + ` values($1, $2, $3, $4)` */

  let id = `${Math.random().toString(16).substring(5)}`
  let result = await orm.model().table('content')
                        .returning(['id', 'title'])
                        .insert({
                          //属性的简写方式
                          id,
                          //来自于请求提交的数据
                          title: ctx.body.title,
                          detail: ctx.body.detail,
                          create_time: Date.now()
                        })
  //默认rows是空数组
  ctx.send(result)
})

app.run(1235)
